package com.global.emc.spring.exception.handler.emcexception;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;

import com.global.emc.core.exception.IEMCException;
import com.global.emc.core.exception.impl.FormValidationEMCException;

/**   
 *  
 * @Description:  [处理FormValidationEMCException类型异常]   
 * @Author:       [Joly_Huang]   
 * @CreateDate:   [2014年2月20日 下午5:14:25]   
 * @UpdateUser:   [Joly_Huang]   
 * @UpdateDate:   [2014年2月20日 下午5:14:25]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *    
 */
public class FormValidationEMCExceptionHandler extends ValidationEMCExceptionHandler {

	@Override
	public boolean supports(IEMCException emcException) {
		return emcException instanceof FormValidationEMCException;
	}

	@Override
	public void handlerException(HttpServletRequest request, HttpServletResponse response, Object handlerMethod, IEMCException emcException, ModelAndView modelAndView) {
		this.logger.error(super.exceptionLog(request, emcException, handlerMethod));
		
		resolverFormValidationEMCException(emcException, request, modelAndView);
		
		super.handlerException(request, response, handlerMethod, emcException, modelAndView);
	}
	
	protected void resolverFormValidationEMCException(IEMCException emcException, HttpServletRequest request, ModelAndView modelAndView) {
		Map<String, Object> model = ((BindException) ((Exception)emcException).getCause()).getBindingResult().getModel();
		for (Map.Entry<String, Object> entry : model.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (value instanceof BindingResult){
				modelAndView.addObject(key, value);
				return;
			}
		}
	}

}
